<template>
  <div class="target-audience-form">
    <!-- 性别选择 -->
    <el-form-item label="性别">
      <el-checkbox-group v-model="form.targetAudience.gender">
        <el-checkbox label="1">男性</el-checkbox>
        <el-checkbox label="2">女性</el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <!-- 年龄范围 -->
    <el-form-item label="年龄范围">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-input-number
              v-model="form.targetAudience.age_range[0]"
              :min="0"
              :max="100"
              placeholder="最小年龄"
          ></el-input-number>
        </el-col>

        <el-col :span="12">
          <el-input-number
              v-model="form.targetAudience.age_range[1]"
              :min="0"
              :max="100"
              placeholder="最大年龄"
          ></el-input-number>
        </el-col>
      </el-row>
    </el-form-item>
    <!-- 兴趣标签 -->
    <el-form-item label="兴趣">
      <el-tag
          v-for="(tag, index) in form.targetAudience.interests"
          :key="index"
          closable
          @close="removeInterest(index)"
      >{{ tag }}</el-tag>
      <el-input
          v-model="newInterest"
          placeholder="输入兴趣并按 Enter 添加"
          @keyup.enter.native="addInterest"
          style="width: 200px; margin-left: 10px"
      ></el-input>
    </el-form-item>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Object,
      default: () => ({
        gender: [],
        age_range: [18, 60],
        interests: []
      })
    }
  },
  data() {
    return {
      newInterest: '',
      form: {
        targetAudience: this.value
      }
    };
  },
  watch: {
    // 监听表单变化，同步到父组件
    'form.targetAudience': {
      deep: true,
      handler(newVal) {
        this.$emit('input', newVal); // 关键：把组装好的对象传给父组件
      }
    }
  },
  methods: {
    // 添加兴趣标签
    addInterest() {
      if (this.newInterest.trim()) {
        this.form.targetAudience.interests.push(this.newInterest.trim());
        this.newInterest = '';
      }
    },
    // 移除兴趣标签
    removeInterest(index) {
      this.form.targetAudience.interests.splice(index, 1);
    }
  }
};
</script>
